<template>
  <div class="bigbox">
    <!-- 表头 -->
    <!-- <div class="header">
      <div class="topbox">
        <span class="span">建筑群</span>
        <span class="spans">
          <el-select size="small" v-model="buildingId" @change="changqiye">
            <el-option v-for="(item,index) in qiyelist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
          </el-select>
        </span>
        <span class="span">用户</span>
        <span>
          <el-select size="small" v-model="customerId" @change="changeyonghu">
            <el-option v-for="(item,index) in yonghulist" :key="index" :label="item.customerName" :value="item.id" class="option"></el-option>
          </el-select>
        </span>
      </div>
    </div> -->
    <div class="leftbox">
            <!-- 树节点过滤 -->
        <div>
        <el-input
          placeholder="输入关键字进行过滤"
          size="small"
          v-model="filterText"
        >
        </el-input>
      </div>
      <!-- 树组件 -->
      <div class="tree">
        <el-tree
          ref="tree"
          node-key="id"
          :props="props"
          :highlight-current="true"
          @node-click="handleNodeClick"
          :default-expanded-keys="zhankaiarr"
          :filter-node-method="filterNode"
          :load="loadNode"
          lazy>
          <template slot-scope="{ node, data }">
            <span :style="{cursor: data.customerName ? 'pointer' : 'no-drop',fontSize:'14px',color:'#606266'}">{{ node.label }}</span>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="rightbox">
          <!-- 第二层盒子 -->
    <div class="bodyone">
      <div class="onebox">
        <div class="title">客户信息</div>
        <div class="little">
          <div class="imte touxiang">
            <img src="../../../../assets/Prepaid/overview/20250211135611.png"  alt="">
          </div>
          <div class="imte">
            <div style="height: 70px;">
              <div>用户名称</div>
              <div class="divs name">
                <el-tooltip class="item" effect="dark" :content="userentity.customerName" placement="top">
                  <span>{{ userentity.customerName }}</span>
                </el-tooltip>
              </div>
            </div>
            <div style="height: 70px;">
              <div class="divs">开户时间：</div>
              <div class="divs time">{{ userentity.openTime }}</div>
            </div>
          </div>
          <div class="imte">
            <div style="height: 70px;">
              <div >联系电话：</div>
              <div class="divs time">{{ userentity.phone }}</div>
            </div>
            <div style="height: 70px;">
              <div class="divs">抄表例日：</div>
              <div class="divs time">{{ userentity.readDay }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="onebox">
        <div class=" display">
          <div class="title">账户信息</div>
          <div>
            <span v-if="userentity.accountState=='正常'">
              <img src="../../../../assets/Prepaid/matrix/md-assignment_turned_in 1@1x (1).png" alt="">
              <span class="zhangchang">正常</span>
            </span>
            <span v-else-if="userentity.accountState=='欠费'">
              <img src="../../../../assets/Prepaid/matrix/riFill-error-warning-fill 1@1x (2).png" alt="">
              <span class="zhangchang">欠费</span>
            </span>
          </div>
        </div>
        <div class="little" style="height: 85%;">
          <div class="item image imte" style="margin-right: 10px;display: flex;align-items: center;justify-content: center;">
            <img style="width: 120px;height: 120px;" src="../../../../assets/Prepaid/overview/20250211133248.png" alt="">
          </div>
          <div class="item">
            <div class="dianfei">电费余额(元)</div>
            <div class="number">{{Math.floor(+userentity.balance)?Math.floor(+userentity.balance):''  }}</div>
          </div>
          <div class="item">
            <div class="dianfei">预计可用天数(天)</div>
            <div class="number">{{Math.floor(+userentity.availableDays)?Math.floor(+userentity.availableDays):''  }}</div>
          </div>
        </div>
      </div>
      <div class="onebox">
        <div class="title">配置信息</div>
        <div class="endbox">
          <div class="endlittle">
            <div>
              <span><img src="../../../../assets/Prepaid/matrix/room.png" alt=""></span>
              <span>房间信息</span>
            </div>
            <div class="loucen">
              {{ userentity.roomList?.slice(0, -1) }}
            </div>
          </div>
          <div class="endlittle">
            <div>
              <span><img src="../../../../assets/Prepaid/matrix/meter.png" alt=""></span>
              <span>表计信息</span>
            </div>
            <div class="loucen">
              {{ userentity.meterList?.slice(0, -1) }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 第三层盒子 -->
    <div class="bodytwo">
       <div class="twobox">
         <div class="texts">交易记录</div>
         <div class="eltable">
           <TableColumn :tableData="tableData" ref="table"
           :tableConfig="tableConfig"></TableColumn>
         </div>
         <div class="fenye">
          <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pageobj.pageNo"
                @current-change="getdatalist"
                :total="+totalCount">
              </el-pagination>
         </div>
       </div>
       <div class="twoboxs">
        <div class="texts">近半年年用电情况</div>
        <div ref="feiyongxx" style="height: 93%;"></div>
       </div>
    </div>
    <!-- 最底层盒子 -->
    <div class="footer">
      <div class="texts">用电情况</div>
      <div class="yongdian" ref="yongdian" style="height: 92%;"></div>
    </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {getkaikuangapi,gettablelistapis,getjinbannianapi,getyuehaonengapi} from '@/api/prwpaid/summarize/UserKanban'
import TableColumn from '@/components/Table/index.vue';
import {gettablelistapi} from '@/api/prwpaid/user-manage/OpenAaccount'
import { getloginlistapi } from '@/api/prwpaid/file-management/Architectural-complex'
export default {
  name: 'CallPoliceIndex',
  components: {
    TableColumn
  },
  data() {
    return {
      yonghulist:[],
      qiyelist:[],
      pageobj: {
        pageNo: 0,
        pageSize:10
      },
      customerId:'',
      buildingId: '',
      tableData: [],
      tableConfig: [
        { label: '序号', type: 'index',width:'80' ,center:'center'},
        { label: '用户', prop:'customerName'},
        { label: '交易类型', prop: 'transactionType' },
        { label: '交易方式', prop: 'transactionWay' },
        { label: '金额（元）', prop: 'amount',center:'right' },
        {
          label: '状态', prop: 'status', center: 'center',
          formatter: (row, column, cellValue, index) => {
            const text= cellValue=='待审核'?'未完成':cellValue
            return text
          }
         },
        { label: '创建时间', prop: 'transactionTime',width:'170' },
        
      ],
      totalCount:'',
      userentity: {},
      props: {
        label: 'treename',
        disabled: 'disabled'
      },
      filterText: '',
      customerName:'',
      zhankaiarr:[]
    };
  },

  async mounted() {
    // 获取建筑群
    // const res = await getloginlistapi()
    // this.qiyelist = res.data.list
    // const localbuildingId= localStorage.getItem('buildingId')
    // const isBuildIdInArray = this.qiyelist.some(item => item.id == localbuildingId);
    // if(isBuildIdInArray){
    //   this.buildingId = localbuildingId?localbuildingId:res.data.list[0].id
    // }else{
    //   this.buildingId = res.data.list[0].id
    // }

    // this.changqiye(this.buildingId)
    // this.getqingkuang([{name:'本月',datalist:[]},{name:'上月',datalist:[]}])
    // this.getfeiyong([])
  },

  methods: {
    // 树节点点击
    handleNodeClick(val){
      if (val.customerName) {
        this.customerId=val.id
        this.customerName = val.customerName
        this.getuserlist(val.id)
      } else {
        this.userentity = {}
        this.tableData = []
        this.totalCount = 0
        this.getfeiyong([])
        this.getqingkuang([{name:'本月',datalist:[]},{name:'上月',datalist:[]}])
      }
    },
    // 树组件懒加载
    async loadNode(node, resolve) {
      const res = await getloginlistapi()
      res.data.list.forEach(ele=>ele['treename']=ele.name)
      if (node.level === 0) {
        // 默认展开第一层
        this.zhankaiarr.push(res.data.list[0].id)
        return resolve(res.data.list) // 最顶层数据渲染为region
      }
      if (node.level === 1) {
        const ress = await gettablelistapi({
          pageNo: 0, pageSize: 500,
          startDate: '', endDate: '', 
          state:'20',buildingId:node.data.id,customerType:''
        })
        ress.data.list.forEach(ele => ele['treename'] = ele.customerName)
        resolve(ress.data.list)
        // 默认选择并模拟点击第一个节点
        this.$refs.tree.setCurrentKey(ress.data.list[0].id)
         return this.handleNodeClick(ress.data.list[0])
         
      }
      if (node.level == 2) {
        return resolve([])
      }
    },
    // 获取表格数据
    async getdatalist() {
     this.$refs.table.loading=true
      // const customerName=this.yonghulist.filter(ele=>ele.id==this.customerId)[0].customerName
      const { data: { list, totalCount } } = await gettablelistapis({
        pageNo: this.pageobj.pageNo - 1, pageSize: this.pageobj.pageSize,
        customerId: this.customerId,customerName:this.customerName
      })
      this.tableData = list
      this.totalCount=totalCount
      this.$refs.table.loading=false
    },
    // 企业下拉
    async changqiye(val) {
      localStorage.setItem('buildingId', val)
      const ress = await gettablelistapi({
          pageNo: 0, pageSize: 500,
        startDate: '', endDate: '', 
        state:'',buildingId:val,customerType:''
      })
      this.yonghulist = ress.data.list
      this.customerId=ress.data.list[0]?.id
      if (this.customerId) {
        this.changeyonghu()
      } else {
        this.userentity = {}
        this.tableData = []
        this.totalCount = 0
        this.getfeiyong([])
        this.getqingkuang([{name:'本月',datalist:[]},{name:'上月',datalist:[]}])
      }
    },
    // 用户下拉
    changeyonghu() {
       if(!this.customerId) return this.$message.warning('请先选择用户')
      this.getuserlist()
    },
    // 获取后台数据
    async getuserlist(customerId) {
      // 获取用户信息
      const {data:{entity}} = await getkaikuangapi({ customerId: customerId })
      this.userentity = entity
      //获取交易记录表格信息
      this.getdatalist()
      // 获取近半年用电情况
      this.getjinbannnian()
      // 获取用电情况
      this.getyongdianqing()
    },
    // 获取近半年用电情况
    async getjinbannnian() {
      var currentDate = new Date();
      var currentYear = currentDate.getFullYear();
      var currentMonth = currentDate.getMonth() + 1; // 月份从0开始，需要加1
      var prevYear = currentYear;
      var prevMonth = currentMonth - 6;
      if (prevMonth <= 0) {
        prevMonth = prevMonth + 12; // 处理跨年的情况
        prevYear = currentYear - 1; // 年份减1
      }
      if (prevMonth < 10) {
        prevMonth = "0" + prevMonth;
      }
      const endMonth= currentYear + "-" + (currentMonth < 10 ? "0" + currentMonth : currentMonth)
      const  startMonth= prevYear + "-" + prevMonth
      console.log(startMonth,endMonth,5555555555);
      
      const {data:{entity}}=await getjinbannianapi({
        startMonth,endMonth,energyType:'ELEC',customerId:this.customerId
      })
      this.getfeiyong(entity.datalist) 
    },
    // 获取近半年年用电情况图表
    getfeiyong(list) {
      var chartDom = this.$refs.feiyongxx
      var myChart = echarts.init(chartDom);
      var option;
      const timeReading=list.map(ele=>ele.timeReading)
      const valueReading = list.map(ele => ele.valueReading)
      option = {
          tooltip: {
          trigger: 'item',
        },
        grid:{
            top: '8%',
          left:'10%',
          right:'5%',
          bottom:'8%'
          },
          xAxis: {
            type: 'category',
            data: timeReading
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: valueReading,
              type: 'bar'
            }
          ]
        };
      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
    //图表响应处理
        myChart.resize();
      });
    },
    // 获取用电情况
    async getyongdianqing() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month = mon < 10 ? '0' + mon : mon
      const time =year+'-' + month
      const { data: { list } } = await getyuehaonengapi({ energyType: 'ELEC', customerId: this.customerId, month:time })
      this.getqingkuang(list)
    },
    // 获取用电情况图表
    getqingkuang(list) {
      var chartDom = this.$refs.yongdian
      var myChart = echarts.init(chartDom);
      var option;
      const array=[]
      const benyuelist=[]
      const shangyuelist=[]
      list.map(ele => {
        if (ele.name == '本月') {
          ele.datalist.map(item => {
            benyuelist.push(item.valueReading)
            array.push(item.timeReading)
          })
        } else if (ele.name == '上月') {
          ele.datalist.map(item => {
            shangyuelist.push(item.valueReading)
          })
        }
       })
      option = {
        grid: {
        top: '15%',
        bottom: '10%',
        left: '3%',
        right: '2%',
    },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        }
      },
      legend: {
        right:10,
        data: ['本月', '上月']
      },
      xAxis: [
        {
          type: 'category',
          data: array,
          axisPointer: {
            type: 'shadow'
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name:'(kWh)'
          // axisLabel: {
          //   formatter: '{value} '
          // }
        },
      ],
      series: [
        {
          name: '本月',
          type: 'bar',
          itemStyle:{
            color:'#1a90fe'
          },
          data: benyuelist
        },
        {
          name: '上月',
          type: 'bar',
          itemStyle:{
            color:'#23cfc4'
          },
          data: shangyuelist
        },

      ]
    };

      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
    //图表响应处理
        myChart.resize();
      });
    },
    // 树节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.treename.indexOf(value) !== -1
    },
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  }
};
</script>

<style lang="scss" scoped>
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.option{
  padding-left: 10px;
}
.bigbox{
  padding: 10px;
  height: 100%;
  display: flex;
  .leftbox{
    width: 300px;
    height: 100%;
    padding: 20px;
    background-color: #fff;
    margin-right: 10px;
    .tree{
      margin-top: 10px;
      height: 95%;
      overflow-y: auto;
    }
  }
  .rightbox{
    flex:1;
  }
  .bodyone{
    margin:0 0 10px 0;
    display: flex;
    justify-content: space-between;
    .onebox{
      width: 32.9%;
      background-color: #fff;
      height: 246px;
      padding: 15px;
      .display{
        display: flex;
        justify-content: space-between;
        height: 25px;
        .zhangchang{
          font-size: 14px;
          color:#349dff;
          margin-left: 10px;
        }
        img{
          vertical-align:middle;
        }
      }
      .title{
        font-weight: 700;
      }
      .little{
        display: flex;
        height: 90%;
        padding-top: 30px;
        .imte{
          width: 33%;
          // height: 195px;
          color: #333;
          img{
            height: 110px;
            width: 110px;
          }
          .divs{
            margin-top: 23px;
          }
          .name{
            font-weight: bold;
            color: black;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .time{
            font-size: 14px;
            color: black;
            font-weight: bold;
          }

        }
        .touxiang{
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .item{
          width: 33%;
          // height: 195px;
          color: #333;
          img{
            // border-radius: 50%;
            width: 100%;
          }
          .number{
            margin-top: 34px;
            font-size: 28px;
            // white-space: nowrap;
            overflow: hidden;
            // text-overflow: ellipsis;
          }
          .dianfei{
            margin-top: 25px;
            font-size: 14px;
          }
        }
      }
      .endbox{
        display: flex;
        justify-content: space-between;
        .endlittle{
          width: 49%;
          margin-top: 10px;
          img{
            vertical-align: middle;
            margin-right: 15px;
          }
          .loucen{
            margin-top: 10px;
            padding: 10px;
            background-color: #f8fafd;
            height: 155px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 6;
            -webkit-box-orient: vertical;
            line-height: 1.5; /* 设置行高 */

          }
        }
      }
    }
  }
  .bodytwo{
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    .twobox{
      width: 66.45%;
      background-color: #fff;
      height: 342px;
      padding: 15px;
      .texts{
        font-weight: bold;
      }
      .eltable{
        margin-top: 10px;
        height: 82%;
      }
      .fenye{
        text-align: right;
      }
    }
    .twoboxs{
      width: 32.9%;
      background-color: #fff;
      height: 342px;
      padding: 15px;
      .texts{
        font-weight: bold;
      }
    }
  }
  .footer{
    // height: 325px;
    height: calc(100% - 608px);
    background-color: #fff;
    padding: 15px;
    .texts{
        font-weight: bold;
      }
  }
}
::v-deep .el-tooltip__popper{
  background-color: rgba(255, 255, 255, 0.5) !important;
}
::v-deep .popper__arrow {
  background-color: rgba(255, 255, 255, 0.5) !important;
}
::v-deep .popper__arrow:after {
  background-color: rgba(255, 255, 255, 0.5) !important;
}

</style>